<?php
declare (strict_types = 1);

namespace command\factory;

use command\lib\Str;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;

/**
 * 自动化操作数据库
 */
class Database
{
    //数据表配置
    private $config = [];

    /**
     * 构造函数，初始化配置
     *
     * @param array $config
     */
    public function __construct($config=[])
    {
        $this->config = array_merge($this->config,$config);
    }

    /**
     * 初始化数据库类
     *
     * @param array $config
     * @return object
     */
    public static function init(array $config)
    {
        $class = new static($config);

        return $class;
    }

    /**
     * 执行创建操作
     *
     * @return void
     */
    public function create()
    {
        
        $sql = '';
        $prefix = Config::get('database.connections.mysql.prefix')??'';
        foreach ($this->parseConfig() as $value) {
            try {
                $sql = $this->buildCreateSql($value['table'],$value['pk'],$value['field'],$value['engine'],$prefix);
                Db::execute($sql);
            } catch (\Throwable $th) {
                Log::error('表：'.$value['table'].'创建失败,原因:'.$th->getMessage());
            }
        }
            
        return true;
    }

    /**
     * 从原始配置解析出数据库配置
     *
     * @return array
     */
    private function parseConfig()
    {
        return $this->config;
    }

    /**
     * 构建创建表语句
     *
     * @param string $table 表名
     * @param string $pk 主键
     * @param array $fieldArr 字段数组
     * @param string $engine 引擎
     * @param string $charset 编码
     * @return void
     */
    private function buildCreateSql($table,$pk,$fieldArr,$engine,$prefix='',$charset='utf8mb4')
    {
        $table = Str::snake($table);
        if(!empty($prefix))$table = $prefix.$table;

        $tempArr = [];
        foreach ($fieldArr as $value) {
            $tempArr[]=implode(' ',$value);
        }

        $autoTimme = [
            "`create_time` datetime DEFAULT NULL COMMENT '创建时间'",
            "`update_time` datetime DEFAULT NULL COMMENT '更新时间'",
            "`delete_time` datetime DEFAULT NULL COMMENT '删除时间'",
        ];

        $tempArr = array_merge($tempArr,$autoTimme);

        $fieldStr = implode(',',$tempArr);

        return "CREATE TABLE `".$table."` (".$fieldStr.",PRIMARY KEY (`".$pk."`) USING BTREE) ENGINE=".$engine." AUTO_INCREMENT=1 DEFAULT CHARSET=".$charset.";";
    }
    
}